package com.chashu.baidumapservice;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;

public class BMapApiDemoApp extends Application {

	private static final String TAG = "BMapApiDemoApp";

	static BMapApiDemoApp mDemoApp;

	BMapManager mBMapMan = null;

	String mStrKey = "44CEEAAD3B9B3DBCA64ED6F17A08238D0B18FC74";
	boolean m_bKeyRight = true;

	static class MyGeneralListener implements MKGeneralListener {
		@Override
		public void onGetNetworkState(int iError) {
			Log.d("MyGeneralListener", "onGetNetworkState error is " + iError);
			Toast.makeText(BMapApiDemoApp.mDemoApp.getApplicationContext(),
					"Network error", Toast.LENGTH_LONG).show();
		}

		@Override
		public void onGetPermissionState(int iError) {
			Log.d("MyGeneralListener", "onGetPermissionState error is "
					+ iError);
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				Toast.makeText(BMapApiDemoApp.mDemoApp.getApplicationContext(),
						"Permission deny! Add key in BMapApiDemoApp.java!", Toast.LENGTH_LONG).show();
				BMapApiDemoApp.mDemoApp.m_bKeyRight = false;
			}
		}
	}

	@Override
	public void onCreate() {
		mDemoApp = this;
		mBMapMan = new BMapManager(this);
		boolean isSuccess = mBMapMan
				.init(this.mStrKey, new MyGeneralListener());
		if (isSuccess) {
			mBMapMan.getLocationManager().setNotifyInternal(10, 5);
			startAlarm();
		} else {
		}
		super.onCreate();
	}

	private void startAlarm() {
		Log.d(TAG, "start alarm");
		AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
		Intent collectIntent = new Intent(this, GetLocationService.class);
		PendingIntent collectSender 
			= PendingIntent.getService(this, 0, collectIntent, 0);
		am.cancel(collectSender);
		am.setRepeating(AlarmManager.ELAPSED_REALTIME
			, SystemClock.elapsedRealtime()
			, 1000 * 1000
			, collectSender);
	}
	
	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		super.onTerminate();
	}

}
